package com.zhu.androidsample.common;

import android.net.Uri;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.zhu.androidsample.util.ToastUtil;
import com.zhu.androidsample.util.VolleyUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 基本的代理控制器。联网请求数据功能。
 * Created by ZCP on 2015/11/17.
 * mail:43426073@qq.com
 */
public abstract class BasePresenter implements Response.ErrorListener, Request.Method {


    public static final String TAG = "DEBUG";
    private BaseActivity activity;

    public BasePresenter(BaseActivity activity) {
        this.activity = activity;
    }

    /**
     * 提供给子类presenter获取对应activity的方法
     *
     * @return activity
     */
    protected BaseActivity getBaseActivity() {
        return activity;
    }

    /**
     * 联网post请求方法
     *
     * @param requestUrl    请求地址
     * @param requestParams 参数容器
     */
    public void postRequest(UrlMap requestUrl, final Map<String, String> requestParams, Response.Listener<String> listener) {
        Log.d(TAG, "postRequest() called with: " + "url = [" + requestUrl + "], requestParams = [" + requestParams + "]");
        StringRequest request = new StringRequest(Request.Method.POST, requestUrl.getUrl(), listener, this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return requestParams;
            }

            //在header中添加参数：apikey。
            //百度apiStore要求key放在header中
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>(super.getHeaders());
                header.put("apikey", Key.BAIDU_KEY);
                return header;
            }
        };

        activity.getMessage(BaseActivity.START_LOADING).sendToTarget();
        VolleyUtil.getQueue().add(request);
    }

    /**
     * 联网get请求方法
     *
     * @param requestUrl    请求地址
     * @param requestParams 参数容器
     */
    public void getRequest(final UrlMap requestUrl, final Map<String, String> requestParams, Response.Listener<String> listener) {
        Log.d(TAG, "getRequest() called with: " + "url = [" + requestUrl + "], requestParams = [" + requestParams + "]");

        String urlWithParams;
        if (requestParams != null) {
            Uri uri = Uri.parse(requestUrl.getUrl());
            Uri.Builder builder = uri.buildUpon();
            for (HashMap.Entry<String, String> entry : requestParams.entrySet()) {
                builder.appendQueryParameter(entry.getKey(), entry.getValue());
            }
            urlWithParams = builder.build().toString();
        } else {
            urlWithParams = requestUrl.getUrl();
        }

        StringRequest request = new StringRequest(Request.Method.GET, urlWithParams, listener, this) {

            //在header中添加参数：apikey。
            //百度apiStore要求key放在header中
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>(super.getHeaders());
                header.put("apikey", Key.BAIDU_KEY);
                return header;
            }
        };
        activity.getMessage(BaseActivity.START_LOADING).sendToTarget();
        VolleyUtil.getQueue().add(request);
    }

    /**
     * 公共的网络层错误回调方法
     * @param volleyError 错误信息包装类
     */
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        //公共的网络错误回调方法
        Log.d(TAG, "onErrorResponse() called with: " + "volleyError = [" + volleyError + "]");
        ToastUtil.show("网络错误，请稍后重试！");

    }

    /**
     * 发送消息，给引用的activity实体一个信号，更新view
     * 轻量级mvp，代替接口通信
     * @param messageKind   activity约定的消息类型
     */
    protected void updateActivity(int messageKind) {
        activity.getMessage(messageKind).sendToTarget();
    }

    /**
     * 发送消息，给引用的activity实体一个信号，更新view
     * 轻量级mvp，代替接口通信
     * @param messageKind activity约定的消息类型
     * @param bean 传递数据
     */
    protected void updateActivity(int messageKind, Object bean) {
        activity.getMessage(messageKind, bean).sendToTarget();
    }

    /**
     * 网络请求成功回调监听器。子类每有一种网络请求，就需要定义个对应的监听器
     * 在onResponse中执行回调业务逻辑
     */
    protected abstract class Listener implements Response.Listener<String> {
        @Override
        public void onResponse(String o) {
            //公共的网络回调方法
            activity.getMessage(BaseActivity.END_LOADING).sendToTarget();
        }
    }

}
